//
//  IssueListViewController.swift
//  GiteeClient
//
//  Created by 王志标 on 2020/10/23.
//

import UIKit
import MJRefresh
import PKHUD
import UITableView_FDTemplateLayoutCell

class IssueListViewController: BaseViewController {
    
    
    var issueTableView:UITableView!
    var cellID = "issuecellid"
    var issueModelArray:[IssueModel]?

    var projectModel:ProjectMdoel!
    var currentPage = 1
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        
    }
    
    init(project: ProjectMdoel) {
        super.init(nibName: nil, bundle: nil)
        self.projectModel = project
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}


// MARK: - 设置界面
extension IssueListViewController {
    
    func setupUI(){
        self.title = "问题"
        var fra = view.bounds
        fra.size.height -= Common.topHeight
        issueTableView = UITableView(frame: fra)
        issueTableView.register(UINib.init(nibName: "IssueTableViewCell", bundle: nil), forCellReuseIdentifier: cellID)
        view.addSubview(issueTableView)
        issueTableView.delegate = self
        issueTableView.dataSource = self
        issueTableView.separatorStyle = .none
        
        let mjH = MJRefreshNormalHeader {
            self.currentPage = 1
            self.loadData(page: self.currentPage)
        }
        mjH?.lastUpdatedTimeLabel.isHidden = true
        issueTableView.mj_header = mjH
        mjH?.beginRefreshing()
        
        let mjF = MJRefreshBackNormalFooter {
            self.currentPage += 1
            self.loadData(page: self.currentPage)
        }
        issueTableView.mj_footer = mjF
        
        
        issueTableView.emptyDataSetDelegate = self
        issueTableView.emptyDataSetSource = self
        
        if #available(iOS 13.0, *) {
            issueTableView.backgroundColor = Colors.backgroundColor
        }
        
        // 设置创建issue按钮
        let addBtn = UIButton(type: .contactAdd)
        addBtn.addTarget(self, action: #selector(createIssue), for: .touchUpInside)
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: addBtn)
    }
    
    
    /// 创建新的issue
    @objc func createIssue(){
        
        if loginCommand() {
            let newVc = NewIssueViewController(project: self.projectModel)
            newVc.delegate = self
            self.navigationController?.pushViewController(newVc, animated: true)
        }
    }
    
    func loginCommand()->Bool{
        
        if UserDefaultTools.getToken() == nil {
            let vc = LoginViewController()
            vc.title = "登陆"
            let loginVC = BaseNavigationController(rootViewController: vc)
            loginVC.modalPresentationStyle = .fullScreen
            if #available(iOS 13.0, *) {
                loginVC.isModalInPresentation = true
            }
            self.present(loginVC, animated: true, completion: nil)
            return false
        }else {
            return true
        }
    }
}


extension IssueListViewController:NewIssueViewControllerDelegate {
    
    func didCreateIssue() {
        loadData(page: 1)
    }
    
    
    func loadData(page: Int){
        
        let url = URLs.V3URL + URLs.PROJECTS + self.projectModel.id.description + "/issues?page=\(self.currentPage)"
       // NSString *strUrl = [NSString stringWithFormat:@"%@%@/%@/issues?private_token=%@&page=%lu", GITAPI_HTTPS_PREFIX, GITAPI_PROJECTS, projectIdStr, [Tools getPrivateToken], (unsigned long)_page];
        
        // 异步加载
        DispatchQueue.global().async {
        
            let result:Result<[IssueModel?]> = NetWorkTool.shared.getArrayRequest(url: url, parameters: nil)
            
            DispatchQueue.main.async {
                if result.code == 0 {
                    if page == 1 {
                        self.issueModelArray = result.data as? [IssueModel]
                    }else {
                        self.issueModelArray?.append(contentsOf: (result.data as? [IssueModel])!)
                        if result.data?.count == 0 {
                            self.issueTableView.mj_footer.endRefreshingWithNoMoreData()
                            return
                        }
                    }
                    self.issueTableView.reloadData()
                }else {
                    HUD.flash(.label(result.message), delay: 2.0)
                }
                self.issueTableView.mj_header.endRefreshing()
                self.issueTableView.mj_footer.endRefreshing()
            }
        }
    }
}


extension IssueListViewController: UITableViewDelegate,UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        self.issueModelArray?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let model = self.issueModelArray![indexPath.row]
        let cell = tableView.dequeueReusableCell(withIdentifier: cellID, for: indexPath) as! IssueTableViewCell
        cell.model = model
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return tableView.fd_heightForCell(withIdentifier: cellID) { (cell) in
            
            (cell as! IssueTableViewCell).model = self.issueModelArray![indexPath.row]
        }
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let model = self.issueModelArray![indexPath.row]
        let vc = IssueDetialViewController(model: model,titles: ["详情","评价"])
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
}
